#!/bin/bash
# stress_test.sh

HOST="localhost"
PORT="8888"
DURATION=60
MAX_CONCURRENT=2000

echo "开始极限压力测试，最大并发: $MAX_CONCURRENT"

# 监控系统资源
monitor_pid=
if command -v pidstat &> /dev/null; then
    pidstat -p $(pgrep multi_reactor_server) 1 > server_stats.log &
    monitor_pid=$!
fi

for conc in 1000 1500 2000 2500 3000; do
    if [ $conc -gt $MAX_CONCURRENT ]; then
        break
    fi
    
    echo "测试并发数: $conc"
    
    success=0
    fail=0
    count=0
    start_time=$(date +%s)
    end_time=$((start_time + DURATION))
    
    while [ $(date +%s) -lt $end_time ] && [ $fail -lt 1000 ]; do
        for i in $(seq 1 100); do
            (
                if echo "stress_test $conc" | nc -w 2 $HOST $PORT > /dev/null 2>&1; then
                    echo "success" >> /tmp/stress_result.$$
                else
                    echo "fail" >> /tmp/stress_result.$$
                fi
            ) &
            count=$((count + 1))
        done
        sleep 0.02
    done
    
    wait
    
    success=$(grep -c "success" /tmp/stress_result.$$ 2>/dev/null || echo 0)
    fail=$(grep -c "fail" /tmp/stress_result.$$ 2>/dev/null || echo 0)
    rm -f /tmp/stress_result.$$
    
    success_rate=$(echo "scale=2; $success * 100 / ($success + $fail)" | bc)
    qps=$(echo "scale=2; $success / $DURATION" | bc)
    
    echo "并发 $conc: 成功=$success, 失败=$fail, 成功率=${success_rate}%, QPS=${qps}"
    
    if [ $(echo "$success_rate < 50" | bc) -eq 1 ]; then
        echo "系统压力过大，停止测试"
        break
    fi
    
    sleep 3
done

if [ -n "$monitor_pid" ]; then
    kill $monitor_pid
fi
